#!/usr/bin/env -S node --no-warnings --loader ts-node/esm
/**
 * Wechaty - Conversational RPA SDK for Chatbot Makers.
 *  - https://github.com/wechaty/wechaty
 */
// https://stackoverflow.com/a/42817956/1123955
// https://github.com/motdotla/dotenv/issues/89#issuecomment-587753552
import 'dotenv/config.js'

import {
  Contact,
  Message,
  ScanStatus,
  WechatyBuilder,
  log,
}                  from 'wechaty'

import qrcodeTerminal from 'qrcode-terminal'
import axios from 'axios';
import sdk from '@baiducloud/sdk';

var BosClient = sdk.BosClient;

const config = {
    endpoint: 'https://fwh.bcebos.com',         //传入Bucket所在区域域名
    credentials: {
        ak: '59c630fbfda248709b0607c7ce9710d0',         //您的AccessKey
        sk: '8c02b4a059ca4f8585775f05d29cccba'       //您的SecretAccessKey
    }
};

const bucket = 'prm-storage-test';//百度云配置
const key = '/nodejsFile/';//百度云配置
const client = new BosClient(config);//百度云初始化

const backUrl = "http://10.124.24.115:8080/risk-web/";


function onScan (qrcode: string, status: ScanStatus) {
  if (status === ScanStatus.Waiting || status === ScanStatus.Timeout) {
    const qrcodeImageUrl = [
      'https://wechaty.js.org/qrcode/',
      encodeURIComponent(qrcode),
    ].join('')
    log.info('StarterBot', 'onScan: %s(%s) - %s', ScanStatus[status], status, qrcodeImageUrl)

    qrcodeTerminal.generate(qrcode, { small: true })  // show qrcode on console

  } else {
    log.info('StarterBot', 'onScan: %s(%s)', ScanStatus[status], status)
  }
}

function onLogin (user: Contact) {
  log.info('StarterBot', '%s login', user)
}


function onLogout (user: Contact) {
  log.info('StarterBot', '%s logout', user)
}

function formatDate(date:Date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  return `${year}${month}${day}`;
}


function getSuffix(str:String) {
  var lastIndex = str.lastIndexOf('.');
  // 如果找不到'.'或者它是字符串中的第一个字符，则返回空字符串
  if (lastIndex === -1 || lastIndex === 0) return '';
  return str.substring(lastIndex + 1);
}

function geRandom(){
  var digits = 6;
  return Math.floor(Math.random() * Math.pow(10, digits));
}

async function onMessage (msg: Message) {
  
  if (msg.text() === 'ding') {//可用来测试是否正常在线
    await msg.say('hahaha')
  }
  if (msg.self()) {
    //console.log('this message is sent by myself!')
    return
   }
   const talker = msg.talker();
   const contact = talker.payload?.name;
   const contactId = talker.id;
   const room = msg.room();
   var text = '';//初始化为空字符串，只有当信息类型为Text时才赋值
   var roomTopic = '';//初始化为空字符串，只有当信息属于群消息时才赋值
   var isRoom = 0;//是否为群消息，默认否
   if(room){
     roomTopic = await room.topic();
     isRoom = 1;
   }
   const fileTypeList = [
    bot.Message.Type.Attachment,
    bot.Message.Type.Audio,
    bot.Message.Type.Image,
    bot.Message.Type.Video,
  ]
  if (fileTypeList.includes(msg.type())) {
    console.log("开始处理文件")
    const fileBox = await msg.toFileBox();
    console.info(`Saving file ${fileBox.name}...`)
    //await fileBox.toFile()
    //上传百度云
    const formattedDate = formatDate(new Date());//日期格式化，形如20241205
    const filekey = key+formattedDate+"/"+fileBox.name;//百度云具体路径
    //查询文件是否已经存在，如果是则修改文件名
    // let  options = {prefix: 'nodejsFile/20241206/'};
    // client.listObjects(bucket, options)
    // .then(function (response:Object) {
    //     var contents = response.body.contents;
    //     for (var i = 0, l = contents.length; i < l; i++) {
    //         console.log(contents[i].key);
    //         if(contents[i].key===fileBox.name){
    //           console.log("同名了")
    //         }
    //     }
    // })
    // .catch(function (error) {
    //     // 查询失败
    //     console.log(error);
    // });
    const bdBuffer = fileBox.toBuffer();//百度云需要的文件流
    const suffix = getSuffix(fileBox.name);//文件后缀
    const msgType = msg.type().toString();//文件类型,1-Attachment,2-Audio,6-Image,15-Video,7-Text
    client.putObject(bucket, filekey,await bdBuffer)
    .then(function(){
        console.log(`文件名： ${fileBox.name}文件上传百度云服务器成功`);
         //上传到服务器
         axios.post(backUrl+'prmData/sys/two/prmBotMsg', {
          contact:contact,
          contactId:contactId,
          isRoom:isRoom,
          roomTopic:roomTopic,
          text:text,
          url: filekey,
          suffix: suffix,
          msgType:msgType
        })
        .then(function() {
          console.log(`文件名： ${fileBox.name} ---文件上传PRM服务器成功`);
          //msg.say(`文件名：${fileBox.name}---文件上传PRM服务器成功`)
        })
        .catch(function() {
          console.log(`-------------${fileBox.name}文件上传PRM服务器失败--------------`);
        });
    })    // 成功
    .catch(function(){
      console.log(`------------${fileBox.name}文件上传百度云服务器失败----------`);
    });      // 失败


  }else if(msg.type()===bot.Message.Type.Text){
    text = msg.text();
    //上传到服务器
    axios.post(backUrl+'prmData/sys/two/prmBotMsg', {
      contact:contact,
      contactId:contactId,
      isRoom:isRoom,
      roomTopic:roomTopic,
      text:text,
      url: '',
      suffix: '',
      msgType:msg.type().toString()
    })
    .then(function() {
      console.log("Text上传PRM服务器成功");
      //msg.say('Text上传PRM服务器成功')
    })
    .catch(function() {
      console.log("-------------Text上传PRM服务器失败--------------");
    });
    // if (room) {
    //   const topic = await room.topic()
    //   console.log(`群名: ${topic}里的 : ${contact?.name()} 说了句: ${text}并随口祝福了一句“诗盛发大财！”`)
    //   //await msg.say(`群名: ${topic}里的 : ${contact?.name()} 说了句: ${text}并随口祝福了一句“诗盛发大财！”`)
    // } else {
    //   console.log(`Contact: ${contact?.name()} Text: ${text}`)
    // }
  }else{
    console.log("该信息类型不做处理");
    return;
  }
  
}

const bot = WechatyBuilder.build({
  name: 'PRM_BOT',
  /**
   * You can specific `puppet` and `puppetOptions` here with hard coding:
   *
  puppet: 'wechaty-puppet-wechat',
  puppetOptions: {
    uos: true,
  },
   */
  /**
   * How to set Wechaty Puppet Provider:
   *
   *  1. Specify a `puppet` option when instantiating Wechaty. (like `{ puppet: 'wechaty-puppet-whatsapp' }`, see below)
   *  1. Set the `WECHATY_PUPPET` environment variable to the puppet NPM module name. (like `wechaty-puppet-whatsapp`)
   *
   * You can use the following providers locally:
   *  - wechaty-puppet-wechat (web protocol, no token required)
   *  - wechaty-puppet-whatsapp (web protocol, no token required)
   *  - wechaty-puppet-padlocal (pad protocol, token required)
   *  - etc. see: <https://wechaty.js.org/docs/puppet-providers/>
   */
  // puppet: 'wechaty-puppet-whatsapp'

  /**
   * You can use wechaty puppet provider 'wechaty-puppet-service'
   *   which can connect to remote Wechaty Puppet Services
   *   for using more powerful protocol.
   * Learn more about services (and TOKEN) from https://wechaty.js.org/docs/puppet-services/
   */
  // puppet: 'wechaty-puppet-service'
  // puppetOptions: {
  //   token: 'xxx',
  // }
})

bot.on('scan',    onScan)
bot.on('login',   onLogin)
bot.on('logout',  onLogout)
bot.on('message',onMessage)
bot.on("friendship", async friendship => {
	console.log(friendship)
    if (friendship.type() === bot.Friendship.Type.Receive) {
        await friendship.accept();
    }
})

bot.start()
  .then(() => log.info('StarterBot', 'Starter Bot Started.'))
  .catch(e => log.error('StarterBot', e))
